package ynu.lcy.elememicroserviceuserauthservice9091.service;



import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import ynu.lcy.dto.User.RegisterDTO;
import ynu.lcy.elememicroservicecommon.constant.UserConstant;
import ynu.lcy.elememicroservicecommon.exception.BusinessException;
import ynu.lcy.elememicroservicecommon.utils.ErrorCode;

import ynu.lcy.elememicroservicecommon.utils.TokenUtils;
import ynu.lcy.elememicroserviceserviceclient.service.FileUploadFeignClient;
import ynu.lcy.elememicroserviceserviceclient.service.UploadService;
import ynu.lcy.elememicroserviceuserauthservice9091.dao.IUserDao;
import ynu.lcy.elememicroserviceuserauthservice9091.entity.User;
import ynu.lcy.elememicroserviceuserauthservice9091.factory.UserBeanFactory;
import ynu.lcy.vo.TokenVo;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import static ynu.lcy.elememicroservicecommon.constant.CommonConstant.ACCESS_TOKEN;


@Service
public class UserService {
    @Autowired
    private IUserDao dao;
    @Resource
    private UserBeanFactory factory;

    @Resource
    private AuthenticationService service;

    @Resource
    private FileUploadFeignClient uploadService;
    public Boolean register(RegisterDTO user){
        //判断用户是否已存在
        User userDB = dao.findUserByuserPhone(user.getUserPhone());
        if (Objects.isNull(userDB)){
            //上传头像
            String avatarUrl = uploadService.upload(user);
            try {
                //抽象反射工厂创建实例
                User instance = factory.getInstance(user.getUserRole());
                instance.setUserAvatar(avatarUrl);
                instance.setUserName(user.getUserName());
                instance.setUserPhone(user.getUserPhone());
                instance.setPassword(user.getPassword());
                instance.setCreateTime(new Date());
                dao.save(instance);
                return true;
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return false;
    }

    /**
     * 通过token获取当前用户
     * */
    public User getLoginUser(HttpServletRequest request){
        return service.getCurrentUser(request,ACCESS_TOKEN);
    }

    /**
     * 重置密码
     * */
    public void resetPassword(String phone,String password){
        User user = dao.findUserByuserPhone(phone);
        //对密码进行md5加密
        String newPwd = DigestUtils.md5DigestAsHex(password.getBytes());
        user.setPassword(newPwd);
        dao.save(user);
        return;
    }

    /**
     * 获取所有用户
     * @return 所有用户
     * */
    public List<User> list(){
        return dao.findAllByUserRole(UserConstant.DEFAULT_ROLE);
    }

}
